package com.lottery.server.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lottery.server.common.JsonResult;
import com.lottery.server.common.ResultCode;
import com.lottery.server.common.exception.BusinessException;
import com.lottery.server.entity.Prize;
import com.lottery.server.service.PrizeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/lottery/prize")
public class PrizeController {
    
    @Autowired
    private PrizeService prizeService;
    
    @GetMapping("/list")
    public JsonResult<Page<Prize>> list(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String name) {
        
        Page<Prize> page = new Page<>(current, size);
        LambdaQueryWrapper<Prize> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name != null, Prize::getName, name);
        
        return JsonResult.success(prizeService.page(page, wrapper));
    }
    
    @GetMapping("/{id}")
    public JsonResult<Prize> getById(@PathVariable Long id) {
        Prize prize = prizeService.getById(id);
        if (prize == null) {
            throw new BusinessException(ResultCode.PRIZE_NOT_FOUND);
        }
        return JsonResult.success(prize);
    }
    
    @PostMapping
    public JsonResult<Prize> save(@RequestBody Prize prize) {
        prizeService.save(prize);
        return JsonResult.success(prize);
    }
    
    @PutMapping
    public JsonResult<Prize> update(@RequestBody Prize prize) {
        if (prize.getId() == null) {
            throw new BusinessException(ResultCode.VALIDATE_FAILED, "奖品ID不能为空");
        }
        if (!prizeService.updateById(prize)) {
            throw new BusinessException(ResultCode.PRIZE_NOT_FOUND);
        }
        return JsonResult.success(prize);
    }
    
    @DeleteMapping("/{id}")
    public JsonResult<Void> delete(@PathVariable Long id) {
        if (!prizeService.removeById(id)) {
            throw new BusinessException(ResultCode.PRIZE_NOT_FOUND);
        }
        return JsonResult.success(null);
    }
} 